﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Xml;
using System.Windows;
using System.Windows.Media;
using System.Text.RegularExpressions;
using System.Globalization;
using System.Threading;
using System.Reflection;
using System.Windows.Controls;
using System.Windows.Markup;

using SharpVectors.Renderer.Xaml;
using SharpVectors.Dom.Svg;

namespace XamlTune
{
    public static class ConvertUtility
    {
        public static string ConvertSvg(string input)
        {
            XamlRenderer renderer = new XamlRenderer();
            SvgWindow window = new SvgWindow(640, 480);
            window.Renderer = renderer;
            renderer.Window = window;

            window.CreateEmptySvgDocument();

            ((SvgDocument)window.Document).LoadXml(input);

            var result = renderer.Render(window.Document as SvgDocument);

            using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
            {
                XamlWriter.Save(result, ms);
                return Encoding.Default.GetString(ms.ToArray());
            }
        }

        public static Canvas LoadSvg(string filename)
        {
            XamlRenderer renderer = new XamlRenderer();
            SvgWindow window = new SvgWindow(640, 480);
            window.Renderer = renderer;
            renderer.Window = window;

            window.CreateEmptySvgDocument();

            ((SharpVectors.Dom.Css.CssXmlDocument)window.Document).LoadFile(filename);

            return renderer.Render(window.Document as SvgDocument);
        }

        public static Canvas ConvertSvg(string filename, Stream output)
        {
            var result = LoadSvg(filename);
            XamlWriter.Save(result, output);
            return result;
        }

        // this doesn't return the canvas so that it can be called without referencing the WPF assemblies directly.
        public static void Svg2Xaml(string sourcePath, string destinationPath)
        {
            using (var stream = File.Create(destinationPath))
            {
                XamlWriter.Save(XamlTune.ConvertUtility.LoadSvg(sourcePath), stream);
            }
        }
    }
}
